package com.xiaodu.acer.phoneplay.data;

import android.content.Context;

import com.xiaodu.acer.phoneplay.common.Constant;
import com.xiaodu.acer.phoneplay.common.apkparset.AndroidApk;
import com.xiaodu.acer.phoneplay.common.util.AppUtils;
import com.xiaodu.acer.phoneplay.presenter.contract.AppManagerContract;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import library.util.ACache;
import retrofit2.Retrofit;
import zlc.season.rxdownload3.RxDownload;
import zlc.season.rxdownload3.core.Mission;

public class AppManagerModel implements AppManagerContract.Model {


    private Context mContext;
    private Retrofit mRetrofit;

    public AppManagerModel(Context context, Retrofit retrofit) {

        this.mContext = context;
        mRetrofit = retrofit;
    }

    @Override
    public Observable<List<Mission>> getDownloadMissions() {
        //获取数据库列表
        Maybe<List<Mission>> allMission = RxDownload.INSTANCE.getAllMission();

        return allMission.toObservable();

    }

    @Override
    public Retrofit getRetrofit() {
        return mRetrofit;
    }


    @Override
    public Observable<List<AndroidApk>> getLocalApks() {

        final String dir = ACache.get(mContext).getAsString(Constant.APK_DOWNLOAD_DIR);
        return Observable.just(scanApks(dir));
    }

    @Override
    public Observable<List<AndroidApk>> getInstalledApps() {

        return Observable.create(new ObservableOnSubscribe<List<AndroidApk>>() {
            @Override
            public void subscribe(ObservableEmitter<List<AndroidApk>> e) throws Exception {
                e.onNext(AppUtils.getInstalledApps(mContext));
                e.onComplete();
            }
        });
    }


    /**
     * 获取已经下载成功的apk
     *
     * @param dir
     * @return
     */
    private List<AndroidApk> scanApks(String dir) {
        File file = new File(dir);

        if (!file.isDirectory()) {
            throw new RuntimeException("is not Dir");
        }
        File[] apks = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return false;
                }
                return f.getName().endsWith(".apk");
            }
        });

        List<AndroidApk> androidApks = new ArrayList<>();

        for (File apk : apks) {
            AndroidApk androidApk = AndroidApk.read(mContext, apk.getPath());
            if (androidApk != null)
                androidApks.add(androidApk);
        }

        return androidApks;


    }


}
